﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraBars.Alerter;
using DevExpress.XtraEditors;
using FileManager_Server.BusinessLogic.WCF.ObjectContainer_Setting;
using FileManager_Server.BusinessLogic.WCF.System_Setting_Service;
using FileManager_Server.PresentationLayer.Properties;
using System.Net;
using FileManager_Server.Utility;

namespace FileManager_Server.PresentationLayer
{
    public partial class MainForm : Form
    {
        delegate void ChangeUI();

        private ServiceHostCollection _serviceHost;
        private ISystemService systemService;
        public MainForm()
        {
            ServerLocalFile.InitFolderUpdateFolder();
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
            Tsmi_SetClientVersion.Click += Tsmi_SetClientVersion_Click;
            listView2.Items.Clear();
            listView1.Items.Clear();
            ObjectContainerInstance.Instance.UnityObject_Container.GetInterfaceService<ISystemService>().InitializeCastle();
            loginNameTip.AutoPopDelay = 5000;
            loginNameTip.InitialDelay = 1000;
            loginNameTip.ReshowDelay = 500;
            loginNameTip.ShowAlways = true;
            loginNameTip.IsBalloon = true;
            loginNameTip.ToolTipIcon = ToolTipIcon.Info;
            loginNameTip.Active = true;
            loginNameTip.ToolTipTitle = "输入提示:";
            var tr = new System.Windows.Forms.Timer();
            tr.Tick += tr_Tick;
            tr.Interval = 60000;
            tr.Enabled = true;
            var mins = 0;
        }

        void Tsmi_SetClientVersion_Click(object sender, EventArgs e)
        {
            var setClientVersion = new SetClientVersion();
            setClientVersion.ShowDialog();
        }

        private double Mins { get; set; }
        void tr_Tick(object sender, EventArgs e)
        {
            Mins += 1;
            var result = Math.Round((Mins/60), 1);
            toolStripStatusLabel2.Text = string.Format("{0} 小时", result);
        }
        private void tsddb_About_Click(object sender, EventArgs e)
        {
            MessageBox.Show("文件柜服务器端", "关于");
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var listItem = new ListViewItem("服务正在启动......");
            listItem.SubItems.Add(new ListViewItem.ListViewSubItem
                                                                  {Text = DateTime.Now.ToString()});
            listView2.Items.Add(listItem);
            systemService =
                ObjectContainerInstance.Instance.UnityObject_Container.GetInterfaceService<ISystemService>();
            _serviceHost = systemService.StartWcfService(tsl_ServerState, listView2, listView1, listView3);
            tsl_ServerState.Image = Resources.run16.ToBitmap();
            tsl_ServerState.Text = "服务器状态：运行";
            var remoteIPAddress = Dns.GetHostAddresses(Dns.GetHostName())[0];
            tsl_ServerIP.Text = "服务器IP：" + remoteIPAddress;
            tsl_ServerPort.Text = "服务器端口：4503/4504/4505/4506";
            toolStripMenuItem1.Enabled = false;
            toolStripMenuItem2.Enabled = true;

        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            toolStripMenuItem1.Enabled = true;
            toolStripMenuItem2.Enabled = false;
            var threadArgs = new ThreadArgs
            {
                ServiceHost = _serviceHost,
                SystemService = systemService
            };
            var parStart = new ParameterizedThreadStart(StopService);
            var stopThread = new Thread(parStart);
            stopThread.Start(threadArgs);
            var listItem = new ListViewItem("正在停止服务......");
            listItem.SubItems.Add(new ListViewItem.ListViewSubItem { Text = DateTime.Now.ToString() });
            listView2.Items.Add(listItem);
            tsl_ServerState.Image = Resources.hold16.ToBitmap();
            this.tsl_ServerState.Text = "服务器状态：停止";
            tsl_ServerIP.Text = "服务器IP：空";
            tsl_ServerPort.Text = "服务器端口：空";
        }
        public bool CloseArgs;

        private void StopService(object args)
        {
            var threadArgs = args as ThreadArgs;
            if (null != threadArgs)
            {
                if (null != threadArgs.SystemService)
                    threadArgs.SystemService.StopWcfService(_serviceHost);
            }
            if (!listView2.InvokeRequired) return;
            var changeUi = new ChangeUI(DelegateSetValue);
            listView2.Invoke(changeUi);
        }
        void DelegateSetValue()
        {
            var listItem = new ListViewItem("服务已停止");
            listItem.SubItems.Add(new ListViewItem.ListViewSubItem { Text = DateTime.Now.ToString() });
            listView2.Items.Add(listItem);
        }


        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            CloseArgs = true;
            Close();
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.WindowState == FormWindowState.Minimized)
                {
                    this.ShowInTaskbar = false;
                    this.MainForm_NotifyIcon.Visible = true;
                    this.MainForm_NotifyIcon.ShowBalloonTip(3, "提示", "系统仍在运行！\n如要打开，请点击图标", ToolTipIcon.Info);
                }
            }
            catch (Exception ex)
            {
            }
        }


        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (CloseArgs == true)
            {
                Environment.Exit(0);
            }
            e.Cancel = true;
            this.WindowState = FormWindowState.Minimized;

        }

        private void MainForm_NotifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Visible = true;
                return;
            }
        }

        private void MainForm_NotifyIcon_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (this.WindowState == FormWindowState.Minimized)
                    this.WindowState = FormWindowState.Normal;

                this.MainForm_NotifyIcon.Visible = false;
                this.ShowInTaskbar = true;
            }
            catch (Exception ex)
            {
            }
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            MainForm_NotifyIcon_DoubleClick(e, e);
        }

        private void 启动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var applicationInfo = ServerLocalFile.ReadApplicationInfo();
            if(null == applicationInfo)
            {
                MessageBox.Show("请先对客户端版本进行设置!");
                var setClientVersion = new SetClientVersion();
                setClientVersion.ShowDialog();
            }
            else
            {
                toolStripMenuItem1_Click(e, e);
                MainForm_NotifyIcon.Icon = Resources.run32;
            }
        }

        private void 停止ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripMenuItem2_Click(e, e);
            MainForm_NotifyIcon.Icon = Resources.hold32;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStripMenuItem3_Click(e, e);
        }
        private ToolTip loginNameTip = new ToolTip();
        private void btn_Send_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_SendText.Text.Trim()))
            {
               // loginNameTip.Show(string.Empty, txt_SendText, 0);
               // loginNameTip.Show("请输入通知内容!", txt_SendText);
                MessageBox.Show("请输入通知内容!");
                return;
            }
            BeginInvoke((EventHandler)delegate
            {
                systemService.NotifyMessage(txt_SendText.Text);
                txt_SendText.Text = "";
            });
            XtraMessageBox.Show(GlobalString.System_Exception_String.SendNormalMessageStr, GlobalString.System_Exception_String.MbxInfoStr, MessageBoxButtons.OK,
                                      MessageBoxIcon.Information);
        }

        private void txt_SendText_TextChanged(object sender, EventArgs e)
        {
            loginNameTip.Hide(txt_SendText);
        }

        private void toolStripMenuItem1_Click_1(object sender, EventArgs e)
        {
            var applicationInfo = ServerLocalFile.ReadApplicationInfo();
            if (null == applicationInfo)
            {
                MessageBox.Show("请先对客户端版本进行设置!");
                var setClientVersion = new SetClientVersion();
                setClientVersion.ShowDialog();
            }
            else
            {
                var listItem = new ListViewItem("服务正在启动......");
                listItem.SubItems.Add(new ListViewItem.ListViewSubItem { Text = DateTime.Now.ToString() });
                listView2.Items.Add(listItem);
                systemService =
                    ObjectContainerInstance.Instance.UnityObject_Container.GetInterfaceService<ISystemService>();
                _serviceHost = systemService.StartWcfService(tsl_ServerState, listView2, listView1, listView3);
                tsl_ServerState.Image = Resources.run16.ToBitmap();
                tsl_ServerState.Text = "服务器状态：运行";
                var remoteIPAddress =
                    Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault(
                        x => x.AddressFamily.Equals(AddressFamily.InterNetwork));
                tsl_ServerIP.Text = "服务器IP：" + remoteIPAddress;
                tsl_ServerPort.Text = "服务器端口：4503/4504/4505";
                toolStripMenuItem1.Enabled = false;
                toolStripMenuItem2.Enabled = true;
            }

        }

        private void toolStripMenuItem2_Click_1(object sender, EventArgs e)
        {
            toolStripMenuItem1.Enabled = true;
            toolStripMenuItem2.Enabled = false;
            var threadArgs = new ThreadArgs
            {
                ServiceHost = _serviceHost,
                SystemService = systemService
            };
            var parStart = new ParameterizedThreadStart(StopService);
            var stopThread = new Thread(parStart);
            stopThread.Start(threadArgs);
            var listItem = new ListViewItem("正在停止服务......");
            listItem.SubItems.Add(new ListViewItem.ListViewSubItem { Text = DateTime.Now.ToString() });
            listView2.Items.Add(listItem);
            tsl_ServerState.Image = Resources.hold16.ToBitmap();
            this.tsl_ServerState.Text = "服务器状态：停止";
            tsl_ServerIP.Text = "服务器IP：空";
            tsl_ServerPort.Text = "服务器端口：空";
        }

        private void toolStripMenuItem3_Click_1(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }
    }
}
